// ERP API 相关类型
import { STORAGE_KEYS, STORAGE_KEY_PREFIX } from './defines';

interface AuthInfo {
    authorization: string;
    ptoken: string;
    account_id?: string;
}

interface ChatOrderResponse {
    data: any; // 根据实际返回数据结构定义
}

interface MessageData {
    chat_id: string;
    messages: any[]; // 根据实际消息结构定义
}

// SOP树形结构数据相关接口
interface SopTreeNode {
    id: number;
    name: string;
    sop_name: string;
    color: string;
    parent_id: number | null;
    disabled: boolean;
    placeholder: string;
    position: number;
    children: SopTreeNode[];
}

interface SopTreeResponse {
    success: boolean;
    msg: string;
    data: SopTreeNode[];
}

// ERP API 相关函数

// 存储认证信息
export async function saveAuthInfo(auth: string, ptoken: string): Promise<void> {
    return new Promise((resolve, reject) => {
        chrome.storage.local.set({
            [STORAGE_KEYS.AUTH]: auth,
            [STORAGE_KEYS.PTOKEN]: ptoken
        }, () => {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve();
            }
        });
    });
}

// 获取认证信息
export async function getAuthInfo(): Promise<AuthInfo> {
    try {
        return new Promise<AuthInfo>((resolve, reject) => {
            // 设置超时处理
            const timeoutId = setTimeout(() => {
                reject(new Error('获取认证信息超时'));
            }, 5000);

            try {
                chrome.storage.local.get([STORAGE_KEYS.AUTH, STORAGE_KEYS.PTOKEN, STORAGE_KEYS.ACCOUNT_ID], (result) => {
                    clearTimeout(timeoutId);
                    
                    // 检查chrome.runtime.lastError
                    if (chrome.runtime.lastError) {
                        console.error('获取存储数据时出错:', chrome.runtime.lastError);
                        reject(new Error(`获取存储数据失败: ${chrome.runtime.lastError.message}`));
                        return;
                    }
                    
                    // 获取账号并去除空格
                    let accountId = result[STORAGE_KEYS.ACCOUNT_ID] || '';
                    if (accountId) {
                        accountId = accountId.replace(/\s+/g, '');
                    }
                    
                    resolve({
                        authorization: result[STORAGE_KEYS.AUTH] || '',
                        ptoken: result[STORAGE_KEYS.PTOKEN] || '',
                        account_id: accountId
                    });
                });
            } catch (err) {
                clearTimeout(timeoutId);
                console.error('访问chrome.storage时出错:', err);
                reject(err);
            }
        });
    } catch (error) {
        console.error('getAuthInfo 函数执行出错:', error);
        // 返回空认证信息，让调用方决定如何处理
        return {
            authorization: '',
            ptoken: '',
            account_id: ''
        };
    }
}

// 获取聊天订单数据 - 已废弃，请使用 whatsappHandler.ts 中的 getChatDataUnified 函数
export async function getErpChatOrderData(chatId: string): Promise<ChatOrderResponse> {
    console.warn('getErpChatOrderData 函数已废弃，请使用 whatsappHandler.ts 中的 getChatDataUnified 函数');
    throw new Error('getErpChatOrderData 函数已废弃，请使用 whatsappHandler.ts 中的 getChatDataUnified 函数');
}

// 发送消息到 ERP
export async function sendErpMessages(chatId: string, messagesData: any[]): Promise<any> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('未获取到认证信息');
        }

        // 获取账户 ID
        const accountId = await new Promise<string>((resolve) => {
            chrome.storage.local.get([STORAGE_KEYS.ACCOUNT_ID], (result) => {
                resolve(result[STORAGE_KEYS.ACCOUNT_ID] || '');
            });
        });

        const payload = {
            chat_id: chatId,
            account_id: accountId,
            messages: messagesData.map(msg => {
                return {
                    message_id: msg.message_id,
                    timestamp: msg.timestamp,
                    message_from_name: msg.message_from_name,
                    body: msg.body
                };
            })
        };

        const response = await fetch('https://tools.kikimami.com/crm/api/syncwam/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify(payload)
        });

        if (!response.ok) {
            throw new Error('发送消息到 ERP 失败');
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('发送消息到 ERP 出错:', error);
        throw error;
    }
}

// 保存 AI 提示结果
export async function saveAIPromptResult(chatId: string, promptId: string, result: string): Promise<any> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('未获取到认证信息');
        }

        const response = await fetch('https://tools.kikimami.com/crm/api/upwact/save-prompt-result', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify({
                chat_id: chatId,
                prompt_id: promptId,
                result: result
            })
        });

        if (!response.ok) {
            throw new Error('保存 AI 提示结果失败');
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('保存 AI 提示结果出错:', error);
        throw error;
    }
}

// 获取跟进状态
export async function getErpFollowStatus(): Promise<any> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('未获取到认证信息');
        }

        const response = await fetch('https://tools.kikimami.com/crm/api/getwhatsappfollowstatus/', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            }
        });

        if (!response.ok) {
            throw new Error('获取跟进状态失败');
        }

        const data = await response.json();
        return data.data;
    } catch (error) {
        console.error('获取跟进状态出错:', error);
        throw error;
    }
}

// 获取提示词列表
export async function fetchAndStoreErpPrompts(authInfo: AuthInfo): Promise<any> {
    try {
        const response = await fetch('https://tools.kikimami.com/crm/api/getprompts/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify({ t: "whatsapp_prompts" })
        });

        if (!response.ok) {
            throw new Error('获取提示词列表失败');
        }

        const data = await response.json();
        
        // 存储提示词列表
        await new Promise<void>((resolve, reject) => {
            chrome.storage.local.set({ [STORAGE_KEYS.PROMPTS]: data }, () => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve();
                }
            });
        });

        return data.data;
    } catch (error) {
        console.error('获取提示词列表出错:', error);
        throw error;
    }
}

// 翻译文本
export async function translateText(text: string, targetLang = 'zh', messageId = ''): Promise<string | null> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('缺少认证信息');
        }

        const response = await fetch('https://tools.kikimami.com/crm/api/crmtranslate/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify({
                text: text,
                source_language: 'auto',
                target_language: targetLang,
                message_id: messageId
            })
        });

        if (!response.ok) {
            throw new Error('翻译请求失败');
        }

        const result = await response.json();
        if (result.data) {
            return result.data;
        }
        throw new Error('翻译结果为空');
    } catch (error) {
        console.error('翻译出错:', error);
        return null;
    }
}

export const generateAIReply = async (promptId: number, chatId: string) => {
  const authInfo = await getAuthInfo();
  if (!authInfo.authorization || !authInfo.ptoken) {
    throw new Error('缺少认证信息');
  }

  const response = await fetch('https://tools.kikimami.com/crm/api/crmaireplyemail/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'authorization': authInfo.authorization,
      'ptoken': authInfo.ptoken
    },
    body: JSON.stringify({
      prompt_id: promptId,
      chat_id: chatId
    })
  });

  if (!response.ok) {
    throw new Error('请求失败');
  }

  const result = await response.json();
  return result;
};

// 自定义提示词生成回复
export const generateCustomAIReply = async (chatId: string, customPrompt: string) => {
  const authInfo = await getAuthInfo();
  if (!authInfo.authorization || !authInfo.ptoken) {
    throw new Error('缺少认证信息');
  }

  const response = await fetch('https://tools.kikimami.com/crm/api/custompromptreply/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'authorization': authInfo.authorization,
      'ptoken': authInfo.ptoken
    },
    body: JSON.stringify({
      chat_id: chatId,
      custom_prompt: customPrompt
    })
  });

  if (!response.ok) {
    throw new Error('请求失败');
  }

  const result = await response.json();
  return result;
};

// 获取dashboard数据，接口。https://tools.kikimami.com/crm/api/getwhatsappstatusdashboard 阐述，当前账号 
export async function getDashboardData(status?: string): Promise<any> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('缺少认证信息');
        }

        // 构建URL，将account_id作为查询参数
        const url = new URL('https://tools.kikimami.com/crm/api/getwhatsappstatusdashboard/');
        if (authInfo.account_id) {
            url.searchParams.append('_serialized', authInfo.account_id);
        }
        
        // 如果提供了status参数，将其添加到URL查询参数中
        if (status) {
            url.searchParams.append('status', status);
        }

        const response = await fetch(url.toString(), {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            }
        });

        if (!response.ok) {
            throw new Error(`获取dashboard数据失败: ${response.status} ${response.statusText}`);
        }

        const data = await response.json();
        return data.data;
    } catch (error: any) {
        console.error('getDashboardData 执行出错:', error);
        // 重新抛出错误，但提供更多上下文
        throw new Error(`获取看板数据失败: ${error.message}`);
    }
}

// 获取AI自动回复建议
export async function getAutoAIReply(chatId: string): Promise<any> {
    try {
        // 触发加载状态事件
        const loadingEvent = new CustomEvent('ai-reply-loading', {
            detail: { chatId }
        });
        window.dispatchEvent(loadingEvent);

        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('缺少认证信息');
        }

        const response = await fetch('https://tools.kikimami.com/crm/api/autoaireply/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify({
                account_serialized: authInfo.account_id,
                chat_id: chatId
            })
        });

        if (!response.ok) {
            throw new Error('获取AI自动回复建议失败');
        }

        const data = await response.json();
        if (data.ChatRemind && data.ChatRemind.content) {  
            // 存储到chat订单数据中
            const storageKey = STORAGE_KEY_PREFIX + chatId;
            await chrome.storage.local.get([storageKey], (result) => {
                const cachedData = result[storageKey] || {};
                cachedData.ChatRemind = data.ChatRemind;
                chrome.storage.local.set({ [storageKey]: cachedData });
            });
            return data.ChatRemind.content;
        }
        return null;
    } catch (error) {
        console.error('获取AI自动回复建议出错:', error);
        // 触发错误状态事件
        const errorEvent = new CustomEvent('ai-reply-error', {
            detail: { 
                chatId,
                error: error instanceof Error ? error.message : '获取AI回复失败'
            }
        });
        window.dispatchEvent(errorEvent);
        throw error;
    } finally {
        // 触发加载完成事件
        const completeEvent = new CustomEvent('ai-reply-complete', {
            detail: { chatId }
        });
        window.dispatchEvent(completeEvent);
    }
}

// 获取SOP树形结构数据
export async function getAISopTree(sop_name: string = "B2B业务", forceRefresh: boolean = false): Promise<SopTreeResponse> {
    // 缓存键 - 根据sop_name区分不同的SOP树
    const cacheKey = `${STORAGE_KEYS.SOP_TREE_CACHE}_${sop_name}`;
    
    // 如果不是强制刷新，尝试从缓存获取数据
    if (!forceRefresh) {
        const cachedData = localStorage.getItem(cacheKey);
        if (cachedData) {
            try {
                const parsedData = JSON.parse(cachedData);
                // 检查缓存是否有效（未过期）- 有效期为7天
                const now = new Date().getTime();
                if (parsedData.timestamp && (now - parsedData.timestamp) < 7 * 24 * 60 * 60 * 1000) {
                    console.log('使用缓存的SOP树数据');
                    return parsedData.data;
                }
            } catch (error) {
                console.error('解析缓存的SOP树数据失败:', error);
                // 缓存解析失败，继续获取新数据
            }
        }
    }

    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('缺少认证信息');
        }

        const response = await fetch('https://tools.kikimami.com/cms/api/aisopdt/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify({
                sop_name: sop_name
            })
        });

        if (!response.ok) {
            throw new Error('获取SOP树形结构数据失败');
        }

        const data = await response.json();
        
        // 缓存数据到本地存储
        const cacheData = {
            timestamp: new Date().getTime(),
            data: data.data
        };
        localStorage.setItem(cacheKey, JSON.stringify(cacheData));
        
        return data.data;
    } catch (error) {
        console.error('获取SOP树形结构数据出错:', error);
        throw error;
    }
}

// 流式AI聊天接口
export const streamAIChat = async (modelId: number, userMessage: string, signal?: AbortSignal, chat_id?: string, account_serialized?: string) => {
  try {
    const authInfo = await getAuthInfo();
    if (!authInfo.authorization || !authInfo.ptoken) {
      throw new Error('缺少认证信息');
    }

    const response = await fetch(`https://tools.kikimami.com/cms/api/aichat/`, {
      method: 'post',
      headers: {
        'Authorization': authInfo.authorization,
        'PTOKEN': authInfo.ptoken,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model_id: modelId,
        user_message: userMessage,
        stream: true,
        chat_id: chat_id,
        account_serialized: account_serialized
      }),
      signal
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return response;
  } catch (error) {
    console.error('AI聊天请求失败:', error);
    throw error;
  }
};

// 创建客户信息
export async function createCustomer(customerData: {
    name: string;
    company: string;
    domain: string;
    mail: string;
    phone: string;
    whatsapp: string;
    country: string;
    source: string;
    tag: string;
    address: string;
    crmcustomercategory_id: number | null;
    chat_id?: string;
}): Promise<any> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('缺少认证信息');
        }

        const response = await fetch('https://tools.kikimami.com/crm/api/crmcustomer/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify(customerData)
        });

        if (!response.ok) {
            throw new Error('创建客户信息失败');
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('创建客户信息出错:', error);
        throw error;
    }
}

// 更新客户信息
export async function updateCustomer(customerId: number, customerData: {
    name: string;
    company: string;
    domain: string;
    mail: string;
    phone: string;
    whatsapp: string;
    country: string;
    source: string;
    tag: string;
    address: string;
    crmcustomercategory_id: number | null;
}): Promise<any> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('缺少认证信息');
        }

        const response = await fetch(`https://tools.kikimami.com/crm/api/crmcustomer/${customerId}/`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify(customerData)
        });

        if (!response.ok) {
            throw new Error('更新客户信息失败');
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('更新客户信息出错:', error);
        throw error;
    }
}

// 获取客户分类列表
export async function getCustomerCategories(): Promise<any> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('缺少认证信息');
        }

        const response = await fetch('https://tools.kikimami.com/crm/api/crmm/?table_name=CRMCustomerCategory', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            }
        });

        if (!response.ok) {
            throw new Error(`获取客户分类失败: ${response.status} ${response.statusText}`);
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('获取客户分类出错:', error);
        throw error;
    }
}

// 解除客户绑定
export async function unbindCustomer(chatId: string): Promise<any> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('缺少认证信息');
        }

        // 获取账号ID
        const account_id = await new Promise<string>((resolve) => {
            chrome.storage.local.get([STORAGE_KEYS.ACCOUNT_ID], (result) => {
                resolve(result[STORAGE_KEYS.ACCOUNT_ID] || '');
            });
        });

        const submitData = {
            _serialized: chatId,
            account_serialized: account_id,
            crmcustomer_id: null, // 设置为空来解除绑定
            table_name: "WhatsappChat"
        };

        const response = await fetch('https://tools.kikimami.com/crm/api/upwact/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify(submitData)
        });

        if (!response.ok) {
            throw new Error('解除客户绑定失败');
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('解除客户绑定出错:', error);
        throw error;
    }
}

